package java0.bio;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  端口8802 方便测试两台一样的服务器
 * @author lxf {@link 286319801@qq.com}
 * @description demo
 * @date 2021-09-25
 */
public class HttpServer02 {

    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 2);
        int port = 8802;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("HTTP Server 启动成功，监听端口：" + port);
        while (true) {
            final Socket socket = serverSocket.accept();
            executorService.execute(() -> service(socket, port));

        }
    }

    private static void service(Socket socket, int port ) {
        try {
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
            printWriter.println("HTTP/1.1 200 OK");
            printWriter.println("Content-Type:text/html;charset=utf-8");
            String boby = Thread.currentThread().getName()+ " >>  hello, nio1。 " +  port;
            printWriter.println("Content-Length:" + boby.getBytes().length);
            printWriter.println();
            printWriter.write(boby);
            printWriter.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
